'use client';

import type { TMetadata } from '@/types';
import { useQuery } from '@tanstack/react-query';
import LoadPage from '@/app/[locale]/load/load';
import ErrorPage from '@/app/[locale]/error/error';
import { queryPostEditInfo } from '@/services/api';
import type { IPostEditInfo } from '@/interfaces';
import EditPostCore from '@/app/[locale]/posts/[id]/edit/core';
import FooterH5IcpPage from '@/app/[locale]/mobile/footerH5Icp';
import FooterH5Page from '@/app/[locale]/mobile/footerH5';

export default function EditPostH5Page({ metadata }: { metadata: TMetadata }) {
  return (
    <>
      <EditPost metadata={metadata} />
      <FooterH5IcpPage metadata={metadata} />
      <FooterH5Page metadata={metadata} />
    </>
  );
}

const EditPost = ({ metadata }: { metadata: TMetadata }) => {
  const queryPostEditInfoQuery = useQuery(
    metadata.all['editPost'].k,
    async (context) => {
      return (await queryPostEditInfo({
        id: context.queryKey[2] + '',
      })) as IPostEditInfo;
    },
    {
      initialData: metadata.all['editPost'].v as IPostEditInfo,
    },
  );

  if (queryPostEditInfoQuery.data) {
    const data = queryPostEditInfoQuery.data;
    return (
      <div className="col p-2">
        <div className="card rounded-5 border-0">
          <div className="card-body px-0">
            <EditPostCore type="editPost" data={data} metadata={metadata} />
          </div>
        </div>
      </div>
    );
  }

  if (queryPostEditInfoQuery.error) {
    return <ErrorPage error={queryPostEditInfoQuery.error} />;
  }

  return <LoadPage />;
};
